
var app = getApp();
Page({
  data: {
    send: false,
    alreadySend: false,
    second: 60,
    disabled: true,
    buttonType: 'default',
    phoneNum: '',
    code: '',
  },

  // 手机号部分
  inputPhoneNum: function (e) {
    let phoneNum = e.detail.value
    if (phoneNum.length === 11) {
      let checkedNum = this.checkPhoneNum(phoneNum)
      if (checkedNum) {
        this.setData({
          phoneNum: phoneNum
        })
        console.log('phoneNum' + this.data.phoneNum)
        this.showSendMsg()
        this.activeButton()
      }
    } else {
      this.setData({
        phoneNum: ''
      })
      this.hideSendMsg()
    }
  },

  checkPhoneNum: function (phoneNum) {
    let str = /^1\d{10}$/
    if (str.test(phoneNum)) {
      return true
    } else {
      wx.showToast({
        title: '手机号不正确',
        image: '../../images/fail.png'
      })
      return false
    }
  },

  showSendMsg: function () {
    if (!this.data.alreadySend) {
      this.setData({
        send: true
      })
    }
  },

  hideSendMsg: function () {
    this.setData({
      send: false,
      disabled: true,
      buttonType: 'default'
    })
  },

  sendMsg: function (event) {
    var that = this;
    var phoneNumber = that.data.phoneNum;
    // wx.setStorageSync('phoneNumber', phoneNumber);
    // //全局变量wx.setStorage({
    // this.globalData.phoneNumber = phoneNumber;

    app.request('/Communication/VerificationCodeForSMS','POST',
    {userId: app.globalData.userId,phoneNumber: phoneNumber},
    res => {
      that.setData({ alreadySend: true,send: false});
      that.timer()
      wx.showToast({ title: '已发送', icon: 'success'})
    },'发送失败');
   

  },

  timer: function () {
    let promise = new Promise((resolve, reject) => {
      let setTimer = setInterval(
        () => {
          this.setData({
            second: this.data.second - 1
          })
          if (this.data.second <= 0) {
            this.setData({
              second: 60,
              alreadySend: false,
              send: true
            })
            resolve(setTimer)
          }
        }
        , 1000)
    })
    promise.then((setTimer) => {
      clearInterval(setTimer)
    })
  },


  // 验证码
  addCode: function (e) {
    this.setData({
      code: e.detail.value
    })

    this.activeButton()

  },

  // 按钮
  activeButton: function () {
    let { phoneNum, code } = this.data;
    if (phoneNum && code) {
      this.setData({
        disabled: false,
        buttonType: 'primary'
      })
    } else {
      this.setData({
        disabled: true,
        buttonType: 'default'
      })
    }
  },

  bindphoneNumber: function (e) {
    var that = this;
    var phoneNumber = that.data.phoneNum;
    //console.log('tel', phoneNumber)
    app.request('/User/PhoneNumber', 'PUT',
      { userId: app.globalData.userId, phoneNumber: phoneNumber },
      res => {
        console.log(res);
        wx.reLaunch({
          url: '../index/index',
        });
      },'绑定失败');
  },

  /* 
    这里使用openid 作为与后端session 连接的标志
    检查是否存在openid，即之前是否登录过
      如果登录过，检查session_key 是否过期
        如果过期了，remove openid 重新执行login 并将用户信息发送到服务器端更新
        如果没过期则返回
      如果没登录过则执行login 并将用户信息发送到服务器更新
  */
  checkSessionAndLogin: function () {
    let that = this;
    let thisOpenId = wx.getStorageSync('openid');

    // 已经进行了登录，检查登录是否过期
    if (thisOpenId) {
      console.log('have openid')
      wx.checkSession({
        success: function () {
          //session_key 未过期，并且在本生命周期一直有效
          wx.navigateBack({});
        },
        fail: function () {
          console.log('but session_key expired');
          // session_key 已经失效，需要重新执行登录流程
          wx.removeStorageSync('openid');
          that.checkSessionAndLogin();
        }
      })
    } else {
      // 没有进行登录则先进行登录操作
      console.log('do not have openid');
      that.loginAndGetOpenid();
    }
  },

  /*sendUserInfoToServer: function () {

    console.log('now send user info to server');
    let userInfo = wx.getStorageSync('userInfo');
    let thisOpenId = wx.getStorageSync('openid');

    userInfo.openid = thisOpenId;

    wx.request({
      url: Domain + '/user/updateUser',
      method: 'POST',
      dataType: 'json',
      data: userInfo,
      success: function (res) {
        res = res.data;
        if (res.code === 0) {
          wx.navigateBack({});
        } else {
          wx.showModal({
            title: 'Sorry',
            content: '同步信息出错~',
          })
        }
      }
    })
  },*/
  //获取用户信息
  info: function (e) {
    wx.getUserInfo({
      success: function (res) {
        console.log(res.userInfo);
        const userInfo = res.userInfo
        const nickName = userInfo.nickName
        const avatarUrl = userInfo.avatarUrl
        const gender = userInfo.gender // 性别 0：未知、1：男、2：女
        const province = userInfo.province
        const city = userInfo.city
        const country = userInfo.country
      }
    })
  }
})
